import json

import redis
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from utils.aliyun.sms import send_sms_single
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django_redis import get_redis_connection


@csrf_exempt
def send_sms(request):
    """发送短信"""
    # 已授权手机号
    phone_num = settings.AUTHORIZED_PHONE_NUM

    tpl = request.GET.get('tpl')
    template_code = settings.ALI_SMS_TEMPLATE.get(tpl)

    if not template_code:
        return HttpResponse("模板不存在")

    code, res = send_sms_single(phone_num=phone_num, template_code=template_code)
    print(code)
    if res:
        if res['statusCode'] == 200:
            return HttpResponse(code + res['body']['Message'])
        else:
            return HttpResponse(str(res))
    return HttpResponse('KeyId or KeySecret Error')


from django import forms
from app01 import models


class UserInfoModelForm(forms.ModelForm):
    class Meta:
        model = models.UserInfo
        fields = '__all__'


class RegisterModelForm(forms.ModelForm):
    # 原有则覆盖
    mobile_phone = forms.CharField(
        label='手机号',
        validators=[RegexValidator(r'^(1[3][4][5][6][7][8][9])\d{9}$', '手机号格式错误'), ]
    )

    password = forms.CharField(label='密码', widget=forms.PasswordInput(), )

    # 新增
    confirm_password = forms.CharField(label='重复密码', widget=forms.PasswordInput(), )
    code = forms.CharField(label='验证码')

    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入' + field.label


def register(request):
    form = RegisterModelForm()
    # django-redis test
    conn = get_redis_connection('default')
    conn.set('nickname', 'ww', ex=10)
    val = conn.get('nickname')

    print(val)
    #####################################
    """用户注册"""
    if request.method == 'POST':
        return render(request, 'app01/register.html', {'form': form})

    code = '02717'
    data = request.GET
    print(data['username'])
    form = UserInfoModelForm(data=data)
    if form.is_valid():
        if code == data.get('code'):
            return HttpResponse('注册成功!')
        return HttpResponse('验证码错误')
    return JsonResponse({'status': False})
